import { dateTimeRangeFormat } from './dateFormat'
import parseHTMLDom from '@/utils/parseHTMLDom'

export const toPercent = (num, decimals = 2) => {
  const n = Number(num)
  if (Number.isNaN(n)) {
    throw new Error('paramater must be num-like')
  }

  return `${(n * 100).toFixed(decimals)}%`
}

export const toThousands = (num) => {
  if (num == null) return num
  const numSplitStr = num.toString().split('.')

  if (numSplitStr.length > 1) {
    const [integer, reset] = numSplitStr
    const thousandsInt = integer.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
    return `${thousandsInt}.${reset}`
  }

  return num.toLocaleString ? num.toLocaleString() : num.toString()
}

export const splite = (raw, mixSymbl = ' ') => {
  return typeof raw === 'string' ? raw.split(mixSymbl) : raw
}

export const join = (raw, mixSymbl = ',') => {
  return Array.isArray(raw) ? raw.join(mixSymbl) : raw
}

export const minuteJoin = (raw, mixSymbl = ',') => {
  if (!Array.isArray(raw) || !raw[1]) return
  return raw.map((item) => item * 60 || 0).join(mixSymbl)
}

export const dateTimeJoin = (raw, mixSymbl = ',') => {
  return join(dateTimeRangeFormat(raw), mixSymbl)
}

export const dateJoin = (raw, mixSymbl = ',') => {
  return join(dateTimeRangeFormat(raw, 'yyyy-MM-dd'), mixSymbl)
}

export const numberJoin = (raw, mixSymbl = ',') => {
  if (Array.isArray(raw) && raw.some((v) => v == null)) {
    return null
  }
  return join(raw, mixSymbl)
}

export const cascaderJoin = (raw, mixSymbl = ',') => {
  if (Array.isArray(raw)) {
    // NOTE 数组 v 可能为空，导致 dp 里最终数据可能会出现 undefined
    const dp = raw.map((v) => v[v.length - 1])
    return join(dp, mixSymbl)
  }
  return raw
}

export const textCutOff = (text, retain) => {
  return typeof text === 'string'
    ? text.length <= retain
      ? text
      : text.slice(0, retain) + '...'
    : text
}

export const filterNextOptions = (value, superOps, nextOps) => {
  if (value.length === 0) {
    return nextOps
  }
  const selectedArray = superOps.filter((item) => value.includes(item.value))
  return nextOps.filter((next) => {
    return selectedArray.reduce((acc, selected) => {
      return next.label.includes(selected.label) || acc
    }, false)
  })
}

export const filterNextValue = (value, options) => {
  return value.filter((item) => {
    return options.reduce((acc, cur) => {
      return cur.value === item || acc
    }, false)
  })
}

// 转义reg中的特殊字符为字符串
export const transRegSpecialSymbol = (regString) => {
  if (typeof regString !== 'string') {
    return regString
  }
  const regSpecial = new RegExp(
    /(\||]|\[|\(|\)|\^|\$|\{|}|\/|\\|\?|\*|\+)/,
    'g'
  )
  return regString.replace(regSpecial, function(match) {
    return `\\${match}`
  })
}

export const addKeyWordsHighlight = (keywords, content, parentTopic) => {
  let contentTemp = content
  let parentTopicTemp = parentTopic
  if (keywords && keywords.length) {
    let keywordArray = []
    let catKeywordArray = []
    const scriptReg = new RegExp('<script', 'gi')
    const imgReg = new RegExp('<img', 'gi')
    keywords.forEach((item) => {
      if (!keywordArray.includes(item.word)) {
        keywordArray.push(item.word)
        catKeywordArray.push({
          word: item.word,
          red: item.cat === '涉政',
        })
      }
    })
    if (contentTemp) {
      contentTemp = parseHTMLDom(contentTemp)
      contentTemp = contentTemp.replace(scriptReg, '<scritp')
      contentTemp = contentTemp.replace(imgReg, '<igm')
      catKeywordArray.forEach((item) => {
        const reg = new RegExp(transRegSpecialSymbol(item.word), 'g')
        contentTemp = contentTemp.replace(
          reg,
          `<span class="keyword_mark${item.red ? '_red' : ''}">${
            item.word
          }</span>`
        )
      })
    }
    if (parentTopicTemp) {
      parentTopicTemp = parseHTMLDom(parentTopicTemp)
      parentTopicTemp = parentTopicTemp.replace(scriptReg, '<scritp')
      parentTopicTemp = parentTopicTemp.replace(imgReg, '<igm')
      catKeywordArray.forEach((item) => {
        const reg = new RegExp(transRegSpecialSymbol(item.word), 'g')
        parentTopicTemp = parentTopicTemp.replace(
          reg,
          `<span class="keyword_mark${item.red ? '_red' : ''}">${
            item.word
          }</span>`
        )
      })
    }
    return {
      contentTemp,
      parentTopicTemp,
    }
  } else {
    return {
      contentTemp,
      parentTopicTemp,
    }
  }
}

export const transWidget = (type) => {
  if (type === 'datetime-ranger') {
    return 'datetimepicker'
  } else if (type === 'date-ranger') {
    return 'datetimepicker'
  }
  return type
}

export const transxProps = (item) => {
  if (item.type === 'datetime-ranger') {
    return {
      type: 'datetimerange',
    }
  } else if (item.type === 'select') {
    return {
      filterable: true,
      multiple: true,
      options: item.options,
    }
  } else if (item.type === 'date-ranger') {
    return {
      type: 'daterange',
      'value-format': 'yyyy-MM-dd',
    }
  }
  return {}
}
